<template>
  <div class="map-dialog">
    <div class="map-container" ref="mapContainer"></div>
    
    <div class="search-panel">
      <el-form :model="searchForm" label-width="80px">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="请输入搜索关键词" @keyup.enter="search"/>
        </el-form-item>
        <el-form-item label="经纬度">
          <el-input v-model="searchForm.coordinates" placeholder="请输入经纬度(逗号分隔)" @keyup.enter="searchByCoordinates"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="clearMarkers">清除标记</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- <div class="instructions">
      <p>使用说明：</p>
      <ul>
        <li>在地图上点击可选择位置</li>
        <li>通过关键字搜索地点</li>
        <li>输入经纬度直接定位（格式：经度,纬度）</li>
        <li>点击"确定"按钮保存所选位置</li>
      </ul>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

// 搜索表单数据
const searchForm = ref({
  keyword: '',
  coordinates: ''
})

// 地图实例和标记
let mapInstance = null
let currentMarker = null

// 获取地图容器
const mapContainer = ref(null)

// 当前选中的坐标
const selectedLocation = ref(null)

// 定义事件发射器
const emit = defineEmits(['select'])

// 导出方法
defineExpose({
  open: () => {
    // 延迟初始化地图，确保DOM完全渲染
    setTimeout(() => {
      initMap()
    }, 100)
  },
  close: () => {
    // 清除标记
    clearMarkers()
  },
  confirmSelection: () => {
    if (selectedLocation.value) {
      emit('select', selectedLocation.value)
    } else {
      alert("请先在地图上选择一个位置")
    }
  }
})

// 初始化地图
const initMap = () => {
  // 检查AMap对象是否存在
  if (typeof AMap === 'undefined') {
    alert('地图加载失败，请检查网络连接或API密钥配置')
    return
  }
  
  if (mapContainer.value) {
    // 如果地图已经存在，先销毁
    if (mapInstance) {
      mapInstance.destroy()
    }
    
    mapInstance = new AMap.Map(mapContainer.value, {
      zoom: 15,
      center: [113.32479, 23.16554],
      viewMode: '3D',
      resizeEnable: true
    })
    
    // 添加地图控件
    mapInstance.addControl(new AMap.Scale())
    mapInstance.addControl(new AMap.NavigationControl())
    
    // 添加点击事件监听
    mapInstance.on('click', handleMapClick)
  }
}

// 搜索功能
const search = () => {
  if (!searchForm.value.keyword) {
    alert("请输入搜索关键词")
    return
  }
  
  // 检查AMap.Geocoder是否存在
  if (typeof AMap.Geocoder === 'undefined') {
    alert('地理编码服务加载失败')
    return
  }
  
  const geocoder = new AMap.Geocoder()
  geocoder.getLocation(searchForm.value.keyword, function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      const location = result.geocodes[0].location
      mapInstance.setCenter([location.lng, location.lat])
      
      // 清除之前的标记
      if (currentMarker) {
        mapInstance.remove(currentMarker)
      }
      
      // 添加新标记
      currentMarker = new AMap.Marker({
        position: [location.lng, location.lat],
        title: searchForm.value.keyword
      })
      mapInstance.add(currentMarker)
      
      // 更新选中位置
      selectedLocation.value = {
        lng: location.lng,
        lat: location.lat
      }
    } else {
      alert("未找到相关地点，请尝试其他关键词")
    }
  })
}

// 通过坐标搜索
const searchByCoordinates = () => {
  if (!searchForm.value.coordinates) {
    alert("请输入经纬度")
    return
  }
  
  try {
    const coords = searchForm.value.coordinates.split(',').map(str => parseFloat(str.trim()))
    if (coords.length >= 2 && !isNaN(coords[0]) && !isNaN(coords[1])) {
      mapInstance.setCenter([coords[0], coords[1]])
      
      // 清除之前的标记
      if (currentMarker) {
        mapInstance.remove(currentMarker)
      }
      
      // 添加新标记
      currentMarker = new AMap.Marker({
        position: [coords[0], coords[1]],
        title: '指定位置'
      })
      mapInstance.add(currentMarker)
      
      // 更新选中位置
      selectedLocation.value = {
        lng: coords[0],
        lat: coords[1]
      }
    } else {
      alert("经纬度格式不正确，请输入数字并用逗号分隔")
    }
  } catch (error) {
    alert("经纬度格式错误: " + error.message)
  }
}

// 监听地图点击事件
const handleMapClick = (e) => {
  // 获取点击位置的坐标
  const position = e.lnglat
  
  // 清除之前的标记
  if (currentMarker) {
    mapInstance.remove(currentMarker)
  }
  
  // 添加新标记
  currentMarker = new AMap.Marker({
    position: [position.lng, position.lat],
    title: '选中位置'
  })
  mapInstance.add(currentMarker)
  
  // 更新选中位置
  selectedLocation.value = {
    lng: position.lng,
    lat: position.lat
  }
}

// 清除所有标记
const clearMarkers = () => {
  if (currentMarker) {
    mapInstance.remove(currentMarker)
    currentMarker = null
  }
  selectedLocation.value = null
  searchForm.value.keyword = ''
  searchForm.value.coordinates = ''
}

// 移除事件监听
onBeforeUnmount(() => {
  if (mapInstance) {
    mapInstance.off('click', handleMapClick)
    mapInstance.destroy()
  }
})

// 在组件挂载后初始化地图
onMounted(() => {
  // 组件挂载时不需要立即初始化地图，在open方法中处理
})
</script>

<style scoped>
.map-dialog {
  width: 100%;
  height: 500px;
  position: relative;
}

.map-container {
  width: 100%;
  height: calc(100% - 180px);
  border: 1px solid #ddd;
}

.search-panel {
  padding: 15px 0;
}

.instructions {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.instructions p {
  margin: 0 0 5px 0;
  font-weight: bold;
}

.instructions ul {
  margin: 0;
  padding-left: 20px;
}

.instructions li {
  margin-bottom: 3px;
  font-size: 12px;
}
</style>